from flask import Flask,request,jsonify
import json
from flask_cors import CORS
from werkzeug.wrappers import response
from db import db1
app=Flask(__name__)
CORS(app)

@app.route('/getshop')
def getshop():
    sql = "select * from shop"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})


@app.route('/shopM')
def shopM():
    id =int(request.args.get('id'))
    sql = "select * from shop where id=%d"%(id)
    res = db1.find(sql)
    return jsonify({'code':200,"list":res})


@app.route('/login',methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data=request.form
    sql = "select * from user where username='%s' and password='%s'"%(data['username'],data['password'])
    res = db1.find(sql)
    if res:
        return jsonify({'code':200,'userid':res['id']})
    else:
        return jsonify({'code':20010,'mes':'用户名或者密码错误'})


@app.route('/shoucang',methods=['POST'])
def shoucang():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form    
    sql = "select gnumber from shop where id=%d"%(int(data['id']))
    res = db1.find(sql)
    count = int(res['gnumber'])
    type = data['type']
    if int(type)==1:
        count+=1
        sql1 = "update shop set gnumber=%d where id=%d"%(count,int(data['id']))
        db1.update(sql1)
        sql3 = "insert into shoucang(userid,shopid) values(%d,%d)"%(int(data['userid']),int(data['id']))
        db1.update(sql3)
        

    else:
        count -= 1
        if count>=0:
            sql2 = "update shop set gnumber=%d where id=%d"(count,int(data['id']))
            db1.update(sql2)
    return jsonify({'code':200})

@app.route('/shoucangs')
def shoucangs():
    userid = int(request.args.get('id'))
    sql = "select shop.name from shoucang inner join shop on shoucang.shopid=shop.id where userid=%d"%(userid)
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})

if __name__ == '__main__':
    app.run(debug=True)
    
